#include "base\macros.h";
WAITINIT(defend);

if(!isServer) exitWith{};

if ((count _this) < 2) exitWith {false};

private ["_grp", "_pos","_debug","_units","_list","_wp","_staticWeapons","_bldgpos","_bldgs"];
_grp = _this select 0;
if (typename _grp == typename objNull) then {
	_grp = group _grp;
};
_pos = _this select 1;
_debug = false;
if (count _this > 2) then {_debug = _this select 2;};

if ((typeName _grp) != (typeName grpNull)) exitWith {false};
if ((typeName _pos) != (typeName [])) exitWith {false};

_grp setBehaviour "AWARE";

_units = (units _grp);

if (_debug) then { diag_log Format["TaskDefend [%1]: Removing %2 WPs from group",_grp, count(waypoints _grp)]; };
{	deleteWaypoint _x;
} foreach (waypoints _grp);

_wp = _grp addWaypoint [_pos, 10];
_wp setWaypointType "HOLD";

// We send units to staticWeapons if any.
_list = nearestObjects [_pos, ["StaticWeapon"], 100];
_staticWeapons = [];
{if ((_x emptyPositions "gunner") > 0) then {_staticWeapons set [count _staticWeapons, _x]}} forEach _list;
{
	if ((count _units) > 0) then {
		if ((random 1) > 0.1) then {
			private ["_unit"];
			_unit = (_units select ((count _units) - 1));
			_unit assignAsGunner _x;
			[_unit] orderGetIn true;
			if (_debug) then { diag_log Format["TaskDefend [%1]: %2 assigned as gunner %3",_grp, _unit, typeof _x]; };
			_units resize ((count _units) - 1);
		};
	};
} forEach _staticWeapons;

// We send units (if any are left) to building pos if any
_bldgpos = [];
if (count _units > 0) then {
	_bldgs = nearestObjects [_pos, ["Building"], 60];
	If (count _bldgs > 0) then {
		{
			private["_i","_y"];
			// We only take the first position of each building.
			_bldarr = [];
			if (!isNil "XfBuildingPosArray") then {
				// Using homebrewn building pos
				_bldarr = [_x,"COMBAT",True, True] call XfBuildingPosArray;
				if (_debug) then { diag_log Format["TaskDefend [%1]: XfBuildingPosArray %2",_grp, _bldarr]; };
				If (count _bldarr > 0) then {
					_bldgpos = [_bldgpos, _bldarr] call XfArrayPushStack;
				};
			};
			if (count _bldarr <= 0) then {
				_found = true;
				_count = 0;
				while {_found} do {
					_y = _x buildingPos _count;
					_found = (_y distance [0,0,0]) > 1;
					if (_found) then {
						_bldgpos set [count _bldgpos, _y];
					};
					_count = _count + 1;
				};
				_found = true;
				_count = 0;
				while {_found} do {
					_y = _x buildingExit _count;
					_found = (_y distance [0,0,0]) > 1;
					if (_found) then {
						_bldgpos set [count _bldgpos, _y];
					};
					_count = _count + 1;
				};
			};
		} forEach _bldgs;
		
		_bldgpos = _bldgpos call XfRandomArray;
		if (_debug) then { diag_log Format["TaskDefend [%1]: BuildingPos to assign %2 and units %3",_grp, count _bldgpos, (count _units)]; };
		{
			(random 1);
			if ((count _units) > 0) then {
				if ((random 1) > 0.1 AND (_x distance [0,0,0]) > 0) then {
					private ["_unit"];
					_unit = (_units select ((count _units) - 1));
					doStop _unit;
					sleep 0.5;
					_unit MoveTo _x;
					_units resize ((count _units) - 1);
					if (_debug) then { diag_log Format["TaskDefend [%1]: Position %2 assigned to %3",_grp, _x, _unit]; };
				};
			};
		} forEach _bldgpos;
	};
};
diag_log Format["TaskDefend [%1]: Positions found for assignment (%2, %3)",_grp, count(_staticWeapons), count(_bldgpos)];

private ["_handle"];
_handle = _units spawn {
	sleep 5;
	{
		if ((random 1) > 0.4) then {
			doStop _x;
			sleep 0.5;
			_x action ["SitDown", _x];	
		};	
	} forEach _this;
};

If (_debug) then {
	_grp spawn {
		private ["_group","_units","_marker","_marker_name"];
		sleep 10;
		_group = _this;
		_units = units _group;
		{
			_marker_name = Format["Unit%1",str(_x)];
			_marker = createMarker[_marker_name,[(getPos _x) select 0,(getPos _x) select 1]];
			_marker setMarkerShape "ICON";
			_marker_name setMarkerType "dot";
			_marker_name setMarkerColor "ColorRed";
			_marker_name setMarkerText str(_x);
		} foreach _units;
		while {alive (leader _group)} do {
			sleep 5;
			{
				private ["_marker_name"];
				_marker_name = Format["Unit%1",str(_x)];
				_marker_name setMarkerPos [getPos _x select 0,getPos _x select 1];
			} forEach _units;
		};
	};
};
true
